<?php
include '../config/auth.php';
$username=$_SESSION['user'];
$room_id= $_GET['room_id'];
/*
 * 判断用户是否存在，进行房间用户添加
 */
$config = include '../config/db.php';
$db = new PDO($config['dsn'],$config['username'],$config['password']);
$statement=$db->prepare('select user_name from user_room where room_id=:room_id ');
$statement->execute(
    [':room_id'=> $room_id]
);
$user=$statement->fetch();
if($username!=$user['user_name']) {
    $statement = $db->prepare('insert into user_room set user_name=:user_name,room_id=:room_id');
    $result = $statement->execute([
        ':user_name' => $username,
        ':room_id' => $room_id
    ]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>星星聊天室</title>
    <link type="text/css" href="../css/ChatRoom.css" rel="stylesheet">
</head>
<body>
<div id="all">
    <div class="top">
        <div class="m">
            <label>欢迎来到<?= $room_id; ?>号房间</label>
        </div>
        <div class="n">
            <div class="w" id="count">

            </div>
            <div class="y">
                <div class="r"><a style="text-decoration: none;" href="Index.php">离开房间</a></div>
            </div>
        </div>
    </div>
    <form  id="myForm" action="../action/ChatRoomAction.php" method="post">
        <div class="home">
        <div class="left" id="chat">
        </div>
        <div class="bottom">
            <div class="middle">
                <form id="myForm" action="../action/ChatRoomAction.php" method="post">
                    <div class="i">
                        <textarea style="height: 100px;width: 670px; border-radius: 8px;"  name="demo"></textarea>
                    </div>
                    <div class="j">
                        <input style="margin-top:15px;height: 80px;width: 100px; font-size: 25px;border-radius: 8px;color: #5bc0de" type="button" id="submit" value="发送">
                    </div>
                </form>
            </div>
        </div>
        </div>
        <div class="right">
            <div class="up">
                <p>当前在线用户</p>
            </div>
            <div class="down" id="user">
            </div>
        </div>
    </form>
</div>
<script>

    //房间用户在线人数统计
    var num=<?php echo $_GET['room_id'];?>;
    var counter=function () {
        var messageElement=document.getElementById('count');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if(this.readyState == 4){
                if(this.status != 200){
                    console.log('服务器出错');
                } else {
                    var result = JSON.parse(this.responseText);
                    messageElement.innerHTML="";
                    if(result.message.length == 0) return;
                    messageElement.innerHTML="当前在线人数："+result.message;
                }
            }
        };
        xhr.open('post','../action/CountAction.php?id='+num);
        xhr.send();
    };
    setInterval(counter,1000);


    //当前房间在线用户同步
    var number=<?php echo $_GET['room_id'];?>;
    var change=function () {
        var messageElement=document.getElementById('user');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if(this.readyState == 4){
                if(this.status != 200){
                    console.log('服务器出错');
                } else {
                    var result = JSON.parse(this.responseText);
                    messageElement.innerHTML="";
                    if(result.message.length == 0) return;
                    for(var i = 0;i<result.message.length;i++) {
                        messageElement.insertAdjacentHTML('beforeend',
                            '<div class="quick">'+
                            '<img src="'+result.message[i].path + '">'+"<br>"+ result.message[i].nickname +
                            '</div>'
                        )
                    }
                }
            }
        };
        xhr.open('post','../action/RightAction.php?id='+number);
        xhr.send();
    };
    setInterval(change,1000);

    //消息数据同步
    var room=<?php echo $_GET['room_id'];?>;
    var lastTime = <?php echo time() ?>;
    var timer=function () {
        var messageElement=document.getElementById('chat');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if(this.readyState == 4){
                if(this.status != 200){
                    console.log('服务器出错');
                } else {
                    var result = JSON.parse(this.responseText);
                    if(result.message.length == 0) return;
                    lastTime = result.time;
                    for(var i = 0;i<result.message.length;i++) {
                        var data = new Date;
                        var y=data.getFullYear(result.message[i].time);
                        var m=data.getMonth(result.message[i].time)+1;
                        var d=data.getDate(result.message[i].time);
                        var h=data.getHours(result.message[i].time);
                        var M=data.getMinutes(result.message[i].time);
                        var s=data.getSeconds(result.message[i].time);
                        if(result.message[i].user_name!='<?php echo $_SESSION['user'];?>'){
                            messageElement.insertAdjacentHTML('beforeend',
                                '<div class="middle">'+
                                '<div class="middle1">'+
                                '<div class="left1">'+
                                '<img src="'+result.message[i].path + '">'+"<br>"+ result.message[i].nickname +
                                '</div>'+
                                '<div class="pre">'+
                                '<div class="up">'
                            + y+'年'+m+'月'+d+'日 '+h+':'+M+':'+s+
                                '</div>'+
                                '<div class="right1">'
                                + result.message[i].message +
                                '</div>'+
                                '</div>'+
                                '</div>'+
                                '</div>'
                            )
                        }else {
                            messageElement.insertAdjacentHTML('beforeend',
                                '<div class="middle">'+
                                '<div class="middle2">'+
                                '<div class="next">'+
                                '<div class="up">'
                                + y+'年'+m+'月'+d+'日 '+h+':'+M+':'+s+
                                '</div>'+
                                '<div class="left2">'
                                + result.message[i].message +
                                '</div>'+
                                '</div>'+
                                '<div class="right2">'+
                                '<img src="'+result.message[i].path + '">'+"<br>"+ result.message[i].nickname +
                                '</div>'+
                                '</div>'+
                                '</div>'
                            )
                        }
                    }
                }
            }
        };
        xhr.open('post','../action/LeftAction.php?lastTime='+lastTime+'&id='+room);
        xhr.send();
    };
    setInterval(timer,2000);


    //控制消息框底部
    function send()
    {
        var e=document.getElementById("aaa");
        var inp=document.getElementById("ccc");
        e.innerText=e.innerText+"\n"+inp.value;
        //e.scrollTop=e.scrollHeight;
    }
    function sc()
    {
        var e=document.getElementById("chat");
        e.scrollTop=e.scrollHeight;
    }
    var s=setInterval("sc()",1000);


    //发送消息
    var username='<?php echo $_SESSION['user'];?>';
    var room_id=<?php echo $room_id;?>;
    var submitElement=document.getElementById('submit');
    var messageElement=document.getElementById('message');
    var formElement=document.getElementById('myForm');
    submitElement.onclick = function (e) {
        e.preventDefault();
        var textElement =document.querySelector('#myForm textarea[name=demo]');
        var content= textElement.value;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {   //等待远程主机做出回应
            if (this.readyState == 4) {
                if (this.status == 200) {
                    var result=JSON.parse(this.responseText);
                    if(result.error==1){
                        messageElement.innerHTML=result.message;
                    }else {
                        textElement.value="";
                        timer();
                    }
                } else {
                    alert('服务器出现异常，请及时联系管理员')
                }
            }
        };
        xhr.open( formElement.method,formElement.action);
        var data=new FormData();
        data.append('username',username);
        data.append('room_id',room_id);
        data.append('message',content);
        xhr.send(data);
    };
</script>
</body>
</html>